# _*_coding:utf-8 _*_
# @Time　　:2021/6/21 22:31
# @Author : mojin
# @Email : 397135766@qq.com
# @File　　  :base_driver.py
# @Software  :PyCharm
from appium import webdriver
from common.all_path import configPath, appPath
import yaml
import os
from common.logger import Logger
from common.app_info import get_devices_version, get_app_name, get_app_launchable_activity, get_app_package_name
from time import sleep
from common.appium_auto_server import open_appium


class BaseDriver:

    def __init__(self, device_info):
        self.device_info = device_info
        cmd = "start /b appium -a 127.0.0.1 -p {0} -bp {1}".format(self.device_info["server_port"],
                                                                   self.device_info["server_port"] + 1)
        try:
            open_appium(cmd, self.device_info["server_port"])
            Logger.info('服务启动成功：%s'%self.device_info)
        except Exception as e:
            Logger.error('服务启动异常！！！（%s;设备信息：%s）'%(str(e),self.device_info))

    def base_driver(self, automationName="appium"):
        fp = open(f"{configPath}//caps.yml", encoding='utf-8')
        # 平台名称、包名、Activity名称、超时时间、是否重置、server_ip、
        desired_caps = yaml.load(fp, Loader=yaml.FullLoader)

        # 设备名称
        desired_caps["deviceName"] = self.device_info['device']

        # 版本信息
        desired_caps["platform_version"] = get_devices_version(desired_caps["deviceName"])

        app_path = os.path.join(appPath, get_app_name(appPath))
        desired_caps['app'] = app_path

        desired_caps['appPackage'] = get_app_package_name()

        desired_caps['appActivity'] = get_app_launchable_activity()

        # udid
        desired_caps["udid"] = self.device_info['device']
        # 系统端口号
        desired_caps["systemPort"] = self.device_info["system_port"]

        if automationName != "appium":
            desired_caps["automationName"] = automationName
        #https://www.cnblogs.com/tianshu/p/10125336.html
        device_cmd=f"http://127.0.0.1:{self.device_info['server_port']}/wd/hub"
        Logger.info(device_cmd)
        Logger.info(desired_caps)
        while True:
            try:
                driver = webdriver.Remote(device_cmd,desired_capabilities=desired_caps)
                #driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
                Logger.info("【%s】设备的driver初始化成功！！！"%desired_caps["deviceName"])
                break
            except Exception as e:
                #Logger.info('driver初始化失败，重新初始化！！！（%s）'%e)
                Logger.info('"【%s】设备的driver初始化失败，正尝试重新初始化！！！（可能是因为上次执行出现异常未正常关闭）'%desired_caps["deviceName"] )#移动端设备8200 systemPort端口服务未关闭被占用
                #pass
            sleep(1)
        #driver = webdriver.Remote(device_cmd,desired_capabilities=desired_caps)


        return driver
